//
//  WmcCloudAlbumSearchResultVC.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/5/14.
//

import MJRefresh
import UIKit

// MARK: - 扩展WmcCloudAlbumSearchResultVC + WmcNavigatorProtocol

extension WmcCloudAlbumSearchResultVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.searchPhotoResult]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcCloudAlbumSearchResultVM()

        if let viewModel = parms.context as? WmcCloudAlbumSearchResultVM {
            vm = viewModel
        }

        let vc = WmcCloudAlbumSearchResultVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcCloudAlbumSearchResultVC + WmcVMProtocol

extension WmcCloudAlbumSearchResultVC: WmcVMProtocol {
    typealias VMType = WmcCloudAlbumSearchResultVM
}

// MARK: - [WmcCloudAlbumSearchResultVC]

class WmcCloudAlbumSearchResultVC: WmcBaseVC, WmcAlbumTransitionProtocol {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchData()
    }

    // Internal

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "搜索结果"

        view.backgroundColor = .wmc_grayH15_E6E6E6

        addSubview(statisticsView)
        addSubview(collectionView)

        statisticsView.addSubview(dateTitleLabel)
        statisticsView.addSubview(dateLabel)
        statisticsView.addSubview(watermarkTitleLabel)
        statisticsView.addSubview(watermarkLabel)
        statisticsView.addSubview(countLabel)
        statisticsView.addSubview(firstLine)
        statisticsView.addSubview(secondLine)

        collectionView.addSubview(emptyView)

        statisticsView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom).offset(8)
            make.left.right.equalToSuperview()
            make.height.equalTo(163)
        }

        dateTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(17)
            make.height.equalTo(25)
        }

        dateLabel.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.centerY.equalTo(dateTitleLabel.snp.centerY)
            make.height.equalTo(25)
            make.width.lessThanOrEqualTo(210)
        }

        firstLine.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(dateTitleLabel.snp.bottom).offset(15)
            make.right.equalTo(-16)
            make.height.equalTo(1)
        }

        watermarkTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(firstLine.snp.bottom).offset(17)
            make.height.equalTo(25)
        }

        watermarkLabel.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.centerY.equalTo(watermarkTitleLabel.snp.centerY)
            make.height.equalTo(25)
            make.width.lessThanOrEqualTo(210)
        }

        secondLine.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(watermarkTitleLabel.snp.bottom).offset(15)
            make.right.equalTo(-16)
            make.height.equalTo(1)
        }

        countLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(secondLine.snp.bottom).offset(17)
        }

        collectionView.snp.makeConstraints { make in
            make.top.equalTo(statisticsView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }

        emptyView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.height.centerX.equalToSuperview()
        }

        var dateStr = ""
        if let startDate = viewModel.startDate {
            dateStr.append(startDate)
        }

        if let endDate = viewModel.endDate {
            dateStr.append(" 至 ")
            dateStr.append(endDate)
        }

        dateLabel.text = dateStr

        var text = "未选择"
        if !viewModel.watermarks.isEmpty {
            var titles: [String] = []
            viewModel.watermarks.forEach { model in
                titles.append(model.data.name)
            }
            text = titles.joined(separator: "，")
        }
        watermarkLabel.text = text
    }

    override func bindViewAction() {
        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.fetchData(showLoading: false)
        })

        collectionView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.loadMore()
        })
    }

    override func bindViewModel() {}

    func deleteMedia(index: Int, vm: WmcMediaBrowseVM) {
        vm.presentDeleteAlert { [weak self] in
            guard let weakSelf = self, index < weakSelf.viewModel.dataSource.count else { return }
            let indexPath: IndexPath = .init(row: index, section: 0)

            WmcHudManager.loading()
            weakSelf.viewModel.deleteImage(indexPath: indexPath, index: index) {
                WmcHudManager.dismiss()
                WmcHudManager.toast("删除成功")
                NotificationCenter.default.post(name: NSNotification.Name("com.watermark.cloudAlbumDataDidChange"), object: self, userInfo: nil)
                NotificationCenter.default.post(name: NSNotification.Name("com.watermark.classifyAlbumDataDidChange"), object: self, userInfo: nil)

                vm.remove(at: index)

                if weakSelf.viewModel.dataSource.isEmpty {
                    weakSelf.fetchData(showLoading: true)
                } else {
                    weakSelf.viewModel.total -= 1
                    weakSelf.countLabel.text = "共搜到：\(weakSelf.viewModel.total)张照片"
                    weakSelf.countLabel.isHidden = weakSelf.viewModel.total == 0
                    weakSelf.collectionView.reloadData()
                }
            } failure: { error in
                WmcHudManager.toast("删除失败")
                WmcHudManager.dismiss()
            }
        }
    }

    // Private

    private lazy var statisticsView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_white_FFFFFF
        return view
    }()

    private lazy var dateTitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH2_323233
        label.font = 17.wmc_font
        label.text = "拍摄时间"
        return label
    }()

    private lazy var dateLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH5_606066
        label.textAlignment = .right
        label.font = 17.wmc_font
        return label
    }()

    private lazy var watermarkTitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH2_323233
        label.font = 17.wmc_font
        label.text = "水印"
        return label
    }()

    private lazy var watermarkLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH5_606066
        label.textAlignment = .right
        label.font = 17.wmc_font
        return label
    }()

    private lazy var countLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH2_323233
        label.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        label.text = "共搜到：0张照片"
        return label
    }()

    private lazy var firstLine: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH19_F5F5F5
        return view
    }()

    private lazy var secondLine: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH19_F5F5F5
        return view
    }()

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let width = (self.view.bounds.width - 38) / 3.0
        layout.itemSize = CGSize(width: width, height: width)
        layout.minimumLineSpacing = 3
        layout.minimumInteritemSpacing = 3
        layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        layout.sectionHeadersPinToVisibleBounds = false

        let collectView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectView.backgroundColor = .wmc_white_FFFFFF
        collectView.delegate = self
        collectView.dataSource = self
        collectView.showsVerticalScrollIndicator = true
        collectView.register(WmcCloudPhotoCell.self, forCellWithReuseIdentifier: "WmcCloudPhotoCell")
        return collectView
    }()

    private lazy var emptyView: WmcCloudAllPhotoEmptyView = {
        let view = WmcCloudAllPhotoEmptyView()
        view.isHidden = true
        return view
    }()

    private func fetchData(showLoading: Bool = true) {
        if showLoading {
            WmcHudManager.loading()
        }

        viewModel.refresh { [weak self] list in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }

            weakSelf.emptyView.isHidden = !list.isEmpty
            weakSelf.collectionView.reloadData()
            weakSelf.collectionView.mj_header?.endRefreshing()

            if weakSelf.viewModel.hasNoMore {
                weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.collectionView.mj_footer?.resetNoMoreData()
            }

            weakSelf.countLabel.text = "共搜到：\(weakSelf.viewModel.total)张照片"
            weakSelf.countLabel.isHidden = weakSelf.viewModel.total == 0

        } failure: { [weak self] _ in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }
            weakSelf.collectionView.mj_header?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")
        }
    }

    private func loadMore() {
        viewModel.loadMore { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.reloadData()
            if weakSelf.viewModel.hasNoMore {
                weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.collectionView.mj_footer?.endRefreshing()
            }
        } failure: { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.mj_footer?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")
        }
    }

    private func pushPhotoBrowser(index: Int) {
        let browseVM = WmcMediaBrowseVM()
        browseVM.topLeftStyle = .backTitle(title: "云相册")
        browseVM.albumType = .cloud
        browseVM.showIndex = index
        browseVM.mediaList = viewModel.browserDataSource
        browseVM.backStyle = .right // 从右侧返回出
        browseVM.shareFriendsCircleMode = .custom
        browseVM.shareWechatMode = .custom

        browseVM.actionBlock = { [weak self] type, index, vm in
            guard let weakSelf = self else { return }
            switch type {
            case .delete:
                weakSelf.deleteMedia(index: index, vm: vm)
            case .save:
                let wmcMedia = weakSelf.viewModel.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    wmcImage.loadUIImage() { image in
                        let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
                        if photoAlbumStatus.info.isAvailable {
                            UIImageWriteToSavedPhotosAlbum(image,
                                                           self,
                                                           #selector(weakSelf.saveImage(_:didFinishSaving:contextInfo:)),
                                                           nil)
                        } else {
                            WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                        }
                    }
                } else if let wmcVideo = wmcMedia as? WmcVideo { // 视频
                    switch wmcVideo.videoType {
                    case let .url(url):
                        let urlString = URL.YP.Create(url).yp.string
                        guard let keyWindow = UIApplication.shared.keyWindow else { return }
                        let progressBarView = WmcProgressBarView.showInView(keyWindow)

                        progressBarView.cancelClosure = {
                            WmcDownloadManager.shared.cancel()
                        }

                        WmcDownloadManager.shared.downloadFile(url: urlString) { value in
                            let progressText = String(format: "正在下载中%.2f", value * 100) + "%"
                            progressBarView.setProgress(Float(value), progressText: progressText)
                        } success: {
                            progressBarView.dismiss()
                            WmcHudManager.toast("已保存到系统相册")
                        } failure: {
                            progressBarView.dismiss()
                            WmcHudManager.toast("保存失败")
                        }
                    default: break
                    }
                }
            case .shareWechat:
                let wmcMedia = weakSelf.viewModel.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    weakSelf.shared(image: wmcImage, scene: .session)
                } else if wmcMedia is WmcVideo { // 视频
                    WmcHudManager.loading()
                    weakSelf.viewModel.fetchVideoShare(index: index) { r in
                        WmcHudManager.dismiss()
                        let icon = UIImage.YP.AppIcon
                        WmcShareManager.shareLink(r.url, title: r.title, description: r.content, thumbImage: icon, scene: .session)
                    } failure: { error in
                        WmcHudManager.dismiss()
                        WmcHudManager.toast(error)
                    }
                }
            case .shareFriendsCircle:
                let wmcMedia = weakSelf.viewModel.browserDataSource[index]
                if let wmcImage = wmcMedia as? WmcImage { // 图片
                    weakSelf.shared(image: wmcImage, scene: .friendCircle)
                } else if wmcMedia is WmcVideo { // 视频
                    WmcHudManager.loading()
                    weakSelf.viewModel.fetchVideoShare(index: index) { r in
                        WmcHudManager.dismiss()
                        let icon = UIImage.YP.AppIcon
                        WmcShareManager.shareLink(r.url, title: r.title, description: r.content, thumbImage: icon, scene: .friendCircle)
                    } failure: { error in
                        WmcHudManager.dismiss()
                        WmcHudManager.toast(error)
                    }
                }
            default: break
            }
        }
        WmcNavigatorManager.push(.imageBrowse, style: .alpha, parms: browseVM)
    }

    private func showShareView(_ shareAlertView: WmcShareAlertView) {
        let height = Wmc_safeAreaBottom + 214
        let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: shareAlertView, contentLayoutBlock: { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(height)
        }))
        presentVC.show()
    }

    private func shared(image: WmcImage?, scene: WmcShareManager.Scene) {
        guard let wmcImage = image else { return }
        wmcImage.loadUIImage { image in
            WmcShareManager.shareImage(image, scene: scene)
        }
    }

    @objc
    private func saveImage(_ image: UIImage, didFinishSaving error: Error?, contextInfo: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("已保存到系统相册")
        }
    }
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

extension WmcCloudAlbumSearchResultVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WmcCloudPhotoCell", for: indexPath) as! WmcCloudPhotoCell
        if let model = viewModel.dataSource.yp.object(at: indexPath.row) {
            cell.bindModel(model)
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let _ = collectionView.cellForItem(at: indexPath) as? WmcCloudPhotoCell else { return }
        self.tabBarController?.tabBar.isHidden = true
        if indexPath.row < viewModel.browserDataSource.count {
            pushPhotoBrowser(index: indexPath.row)
        }
    }
}
